package cn.lingyangwl.agile.infra.job.service.impl;

import cn.lingyangwl.agile.common.core.exception.TaskException;
import cn.lingyangwl.agile.model.BasePlusPO;
import cn.lingyangwl.agile.infra.job.constants.JobCons;
import cn.lingyangwl.agile.infra.job.mapper.JobInfoMapper;
import cn.lingyangwl.agile.infra.job.model.entity.JobInfo;
import cn.lingyangwl.agile.infra.job.model.rqrs.JobPageReq;
import cn.lingyangwl.agile.infra.job.service.IJobInfoService;
import cn.lingyangwl.agile.infra.job.utils.CronUtils;
import cn.lingyangwl.agile.infra.job.utils.ScheduleUtils;
import cn.lingyangwl.agile.tenant.core.utils.TenantUtils;
import cn.lingyangwl.framework.core.utils.spring.SpringUtils;
import cn.lingyangwl.framework.mybatis.plus.utils.PageUtil;
import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.framework.tool.core.exception.Assert;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 定时任务调度信息 服务层
 * 
 * @author shenguangyang
 */
@Slf4j
@Service
public class JobInfoServiceImpl implements IJobInfoService {
    @Resource
    private Scheduler scheduler;

    @Resource
    private JobInfoMapper jobInfoMapper;

    /**
     *
     */
    @Override
    public void init() throws Exception {
        scheduler.clear();
        TenantUtils.executeIgnore(() -> {
            try {
                List<JobInfo> jobList = jobInfoMapper.selectList(new QueryWrapper<>());
                for (JobInfo job : jobList) {
                    ScheduleUtils.createScheduleJob(scheduler, job);
                }
            } catch (Exception e) {
                log.error("error: ", e);
                throw new BizException(e.getMessage());
            }
        });
    }

    @Override
    public IPage<JobInfo> pageJob(JobPageReq req) {
        LambdaQueryWrapper<JobInfo> lqw = getLqw(req);
        IPage<JobInfo> pageRq = PageUtil.to(req);
        return jobInfoMapper.selectPage(pageRq, lqw);
    }

    /**
     * 获取quartz调度器的计划任务列表
     * 
     * @param req 调度信息
     */
    @Override
    public List<JobInfo> listJob(JobPageReq req) {
        return jobInfoMapper.selectList(getLqw(req));
    }

    private LambdaQueryWrapper<JobInfo> getLqw(JobPageReq req) {
        LocalDateTime beginTime = req.getBeginLocalDateTime();
        LocalDateTime endTime = req.getEndLocalDateTime();
        return JobInfo.lqw()
                .like(StringUtils.isNotEmpty(req.getJobName()), JobInfo::getJobName, req.getJobName())
                .eq(StringUtils.isNotEmpty(req.getJobGroup()), JobInfo::getJobGroup, req.getJobGroup())
                .eq(StringUtils.isNotEmpty(req.getStatus()), JobInfo::getStatus, req.getStatus())
                .like(StringUtils.isNotEmpty(req.getInvokeTarget()), JobInfo::getInvokeTarget, req.getInvokeTarget())
                .ge(Objects.nonNull(beginTime), JobInfo::getCreatedAt, beginTime)
                .le(Objects.nonNull(endTime), JobInfo::getCreatedAt, endTime)
                .orderByDesc(BasePlusPO::getCreatedAt);
    }

    /**
     * 通过调度任务ID查询调度信息
     * 
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public JobInfo getById(Long jobId) {
        return jobInfoMapper.selectById(jobId);
    }

    /**
     * 暂停任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public int pauseJob(JobInfo job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(JobCons.Status.PAUSE.getValue());
        int rows = jobInfoMapper.updateById(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public int resumeJob(JobInfo job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(JobCons.Status.NORMAL.getValue());
        int rows = jobInfoMapper.updateById(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(Long jobId) throws SchedulerException {
        JobInfo job = jobInfoMapper.selectById(jobId);
        String jobGroup = job.getJobGroup();
        int rows = jobInfoMapper.deleteById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     * 
     * @param jobIds 需要删除的任务ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> jobIds) throws SchedulerException {
        for (Long jobId : jobIds) {
            SpringUtils.getAopProxy(this).deleteById(jobId);
        }
    }

    /**
     * 任务调度状态修改
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public int changeStatus(JobInfo job) throws SchedulerException {
        int rows = 0;
        String status = job.getStatus();
        if (JobCons.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job);
        } else if (JobCons.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional
    public void execute(JobInfo job) throws SchedulerException {
        JobInfo properties = jobInfoMapper.selectById(job.getId());
        Assert.notNull(properties, "任务不存在");
        String jobGroup = properties.getJobGroup();
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(JobCons.TASK_PROPERTIES, properties);
        scheduler.triggerJob(ScheduleUtils.getJobKey(job.getId(), jobGroup), dataMap);
    }

    /**
     * 新增任务
     * 
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional
    public int save(JobInfo job) throws SchedulerException, TaskException {
        job.setStatus(JobCons.Status.PAUSE.getValue());
        int rows = jobInfoMapper.insert(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * 更新任务的时间表达式
     * 
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJobById(JobInfo job) throws SchedulerException, TaskException {
        JobInfo properties = getById(job.getId());
        int rows = jobInfoMapper.updateById(job);
        if (rows > 0) {
            JobInfoServiceImpl thisProxy = SpringUtils.getAopProxy(this);
            thisProxy.updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    /**
     * 更新任务
     * 
     * @param job 任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(JobInfo job, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 校验cron表达式是否有效
     * 
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }
}